1829E - The Lakes - CodeForces Solution


dfs and similar dsu graphs implementation

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ld double
#define vi  vector<int>
#define vvi vector<vi>
#define pii pair<int,int>
#define vpii vector<pair<int,int>>
#define all(v) v.begin(),v.end()
#define eb emplace_back
#define endl '\n'
const int M=1e9+7;
const ld eps = 1e-9;
const int INF=1e17;
int dfs(vvi &matrix,vvi& vis,int i,int j,int n, int m){
    vis[i][j]=1;
    int cs=matrix[i][j];
    int dx[]={1,-1,0,0};
    int dy[]={0,0,1,-1};
    for(int k=0;k<4;k++){
        int nx=dx[k]+i;
        int ny=dy[k]+j;
        if(nx>=0 && nx<n && ny>=0 && ny<m && matrix[nx][ny]>0 && !vis[nx][ny]){
            int sc=dfs(matrix,vis,nx,ny,n,m);
            cs+=sc;
        }
    }
    return cs;
}
void solve()
{  
    int n,m;
    cin>>n>>m;
    vvi a(n,vi(m));
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++) cin>>a[i][j];
    }    
    vvi vis(n,vi(m,0));
    int largest=0;
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(!vis[i][j] && a[i][j]>0){
                int sz=dfs(a,vis,i,j,n,m);
                largest=max(largest,sz);
            }
        }
    }
    cout<<largest<<'\n';
}
int32_t main() 
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);

    int ff=1;
    std::cin>>ff;
    while(ff--)
        solve();
    return 0;
 
}


Comments

Submit
0 Comments
More Questions

275. H-Index II
274. H-Index
260. Single Number III
240. Search a 2D Matrix II
238. Product of Array Except Self
229. Majority Element II
222. Count Complete Tree Nodes
215. Kth Largest Element in an Array
198. House Robber
153. Find Minimum in Rotated Sorted Array
150. Evaluate Reverse Polish Notation
144. Binary Tree Preorder Traversal
137. Single Number II
130. Surrounded Regions
129. Sum Root to Leaf Numbers
120. Triangle
102. Binary Tree Level Order Traversal
96. Unique Binary Search Trees
75. Sort Colors
74. Search a 2D Matrix
71. Simplify Path
62. Unique Paths
50. Pow(x, n)
43. Multiply Strings
34. Find First and Last Position of Element in Sorted Array
33. Search in Rotated Sorted Array
17. Letter Combinations of a Phone Number
5. Longest Palindromic Substring
3. Longest Substring Without Repeating Characters
1312. Minimum Insertion Steps to Make a String Palindrome